package org.jet.emall.reptile.service;

import org.jet.emall.mapper.*;
import org.jet.emall.po.*;
import org.jet.emall.reptile.pojo.ProductInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class ProductInfoServiceImpl implements ProductInfoService{

    @Autowired
    private TbProdCateMapper prodCateMapper;

    @Autowired
    private TbProdSpuMapper prodSpuMapper;

    @Autowired
    private TbProdBrandMapper prodBrandMapper;

    @Autowired
    private TbProdCateBrandMapper prodCateBrandMapper;

    @Autowired
    private TbProdSkuMapper prodSkuMapper;

    @Autowired
    private TbProdSpecMapper prodSpecMapper;

    @Autowired
    private TbProdSpecGroupMapper prodSpecGroupMapper;

    @Autowired
    private TbProdSpecOptionMapper prodSpecOptionMapper;

    @Autowired
    private TbProdSkuSpecOptionMapper prodSkuSpecOptionMapper;


    @Autowired
    private TbProdAttrMapper prodAttrMapper;

    @Autowired
    private TbProdAttrOptionMapper prodAttrOptionMapper;

    @Autowired
    private TbProdSkuAttrOptionMapper prodSkuAttrOptionMapper;

    @Autowired
    private TbProdSpuImageMapper prodSpuImageMapper;

    @Autowired
    private TbProdSkuImageMapper prodSkuImageMapper;

    @Autowired
    private TbProdSelectionMapper prodSelectionMapper;

    private long count = 0;

//    @Transactional
    @Override
    synchronized public void handleData(ProductInfo product){
        TbProdSkuExample exx = new TbProdSkuExample();
        exx.createCriteria().andCodeEqualTo(product.getSkuCode());
        List<TbProdSku> prodSkus = prodSkuMapper.selectByExample(exx);
        if(prodSkus!=null&&!prodSkus.isEmpty()) {
            System.out.println("取消保存...,因为已经存在");
            return;
        }
        //System.out.println("处理数据:"+product);
        System.out.println("保存第["+count+++"]个product信息");
        // 保存分类信息
        TbProdCate cate1 =null;
        TbProdCate cate2 =null;
        TbProdCate cate3 =null;
        TbProdCateExample ex = new TbProdCateExample();
        TbProdCateExample.Criteria criteria = ex.createCriteria();
        criteria.andNameEqualTo(product.getCate3())
                .andIsFloorEqualTo((byte)0);
        List<TbProdCate> cate3s = prodCateMapper.selectByExample(ex);
        if(cate3s==null || cate3s.isEmpty()){


            TbProdCateExample exa1 = new TbProdCateExample();
            exa1.createCriteria().andNameEqualTo(product.getCate2())
                                .andIsFloorEqualTo((byte)1)
                                .andPidNotEqualTo(0);
            List<TbProdCate> cate2s = prodCateMapper.selectByExample(exa1);
            if(cate2s==null || cate2s.isEmpty()){

                criteria.andNameEqualTo(product.getCate1());
                TbProdCateExample exa2 = new TbProdCateExample();
                exa2.createCriteria().andNameEqualTo(product.getCate1())
                                    .andPidEqualTo(0);
                List<TbProdCate> cate1s = prodCateMapper.selectByExample(exa2);
                if(cate1s==null || cate1s.isEmpty()){
                    //插入cate1
                    cate1 = new TbProdCate();
                    cate1.setName(product.getCate1());
                    cate1.setIsFloor((byte)1);
                    cate1.setLevel((byte)1);

                    prodCateMapper.insertSelective(cate1);
                }else{
                    cate1 = cate1s.get(0);
                }
                cate2 = new TbProdCate();
                cate2.setName(product.getCate2());
                cate2.setIsFloor((byte)1);
                cate2.setPid(cate1.getId());
                cate2.setLevel((byte)2);
                prodCateMapper.insertSelective(cate2);
                //插入cate2
            }else{
                cate2 = cate2s.get(0);
            }
            cate3 = new TbProdCate();
            cate3.setPid(cate2.getId());
            cate3.setName(product.getCate3());
            cate3.setIsFloor((byte)0);
            cate3.setLevel((byte)3);
            prodCateMapper.insertSelective(cate3);
            //插入cate3
        }else{
            cate3 = cate3s.get(0);
        }

        //保存本sku对应的品牌
        TbProdBrand brand = getBrand(product.getBrand());
        if(null==brand){
            brand = saveBrand(cate3.getId(),product.getBrand());
        }else{
            TbProdCateBrandExample ex1 = new TbProdCateBrandExample();
            ex1.createCriteria().andCateIdEqualTo(cate3.getId())
                    .andBrandIdEqualTo(brand.getId());
            long l = prodCateBrandMapper.countByExample(ex1);
            if(l<1){
                TbProdCateBrand tbProdCateBrand = new TbProdCateBrand();
                tbProdCateBrand.setBrandId(brand.getId());
                tbProdCateBrand.setCateId(cate3.getId());
                prodCateBrandMapper.insertSelective(tbProdCateBrand);
            }
        }



        //保存所有品牌,品牌与分类的关联
        if(product.getBrands()!=null&& product.getBrands().size()>0) {
            saveBrands(cate3.getId(), product.getBrands());
        }



        //保存spu信息
        TbProdSpuExample ex3 = new TbProdSpuExample();
        ex3.createCriteria().andCodeEqualTo(product.getSpuCode());

        List<TbProdSpu> tbProdSpus = prodSpuMapper.selectByExample(ex3);
        TbProdSpu spu = null;
        if(tbProdSpus==null||tbProdSpus.isEmpty()){
            spu = new TbProdSpu();
            spu.setBrandId(brand.getId());
            spu.setName(product.getPname());
            spu.setCode(product.getSpuCode());
            spu.setCateId(cate3.getId());
            spu.setBrief(product.getPname());
            prodSpuMapper.insertSelective(spu);

            if(product.getDetails()!=null && product.getDetails().size()>0) {
                TbProdSpuImage image = new TbProdSpuImage();
                image.setSpuId(spu.getId());
                for(String imgUrl:product.getDetails()){
                    TbProdSpuImageExample exy = new TbProdSpuImageExample();
                    exy.createCriteria().andImageEqualTo(imgUrl).andSpuIdEqualTo(spu.getId());
                    List<TbProdSpuImage> tbProdSpuImages = prodSpuImageMapper.selectByExample(exy);
                    if(tbProdSpuImages!=null&& !tbProdSpuImages.isEmpty()) {
                        continue;
                    }
                    image.setImage(imgUrl);
                    prodSpuImageMapper.insertSelective(image);
                }
            }




        }else{
            spu = tbProdSpus.get(0);
        }


        //保存sku信息
        TbProdSku tbProdSku = new TbProdSku();
        tbProdSku.setCode(product.getSkuCode());
        tbProdSku.setName(product.getTitle());
        tbProdSku.setSpuId(spu.getId());
        tbProdSku.setCount(1000);
        try {

            long price = Long.parseLong(product.getPrice())*100;
            tbProdSku.setPrice(price);
        }catch (Exception e) {
            System.out.println("价格转换失败...,priceString="+product.getPrice());
        }
        prodSkuMapper.insertSelective(tbProdSku);

        //保存可选项
        product.getSelection().entrySet().forEach((entry->{
            TbProdSelection selection = new TbProdSelection();
            selection.setSkuId(tbProdSku.getId());
            selection.setTitle(entry.getKey());
            selection.setValue(entry.getValue());
            prodSelectionMapper.insertSelective(selection);
        }));


        //保存sku的图片
        List<String> images = product.getImages();
        TbProdSkuImage image = new TbProdSkuImage();
        image.setSkuId(tbProdSku.getId());
        image.setImage(images.get(0));
        image.setLargeImage(product.getImg());
        prodSkuImageMapper.insertSelective(image);
        image.setLargeImage(null);
        TbProdSkuImageExample exy = new TbProdSkuImageExample();
        for(int i=1;i<images.size();i++){

            exy.clear();
            exy.createCriteria().andSkuIdEqualTo(tbProdSku.getId())
                    .andImageEqualTo(images.get(i));
            List<TbProdSkuImage> tbProdSkuImages = prodSkuImageMapper.selectByExample(exy);
            if(tbProdSkuImages!=null&&!tbProdSkuImages.isEmpty()) {
                continue;
            }
            String imageUrl = images.get(i);
            image.setImage(imageUrl);
            prodSkuImageMapper.insertSelective(image);
        }

        //保存属性
        if(product.getAttrs()!=null){
            for(Map.Entry<String,String> entry: product.getAttrs().entrySet()){
                String attrName = entry.getKey();
                TbProdAttr tbProdAttr = null;
                TbProdAttrExample ex4 = new TbProdAttrExample();
                ex4.createCriteria().andNameEqualTo(attrName);
                List<TbProdAttr> attrs = prodAttrMapper.selectByExample(ex4);
                if(attrs==null||attrs.isEmpty()){
                    tbProdAttr = new TbProdAttr();
                    tbProdAttr.setName(attrName);
                    tbProdAttr.setCateId(cate3.getId());
                    prodAttrMapper.insertSelective(tbProdAttr);
                }else{
                    tbProdAttr = attrs.get(0);
                }
                String attrOptionVal = entry.getValue();
                TbProdAttrOption tbProdAttrOption = null;
                TbProdAttrOptionExample ex5 = new TbProdAttrOptionExample();
                ex5.createCriteria().andValEqualTo(attrOptionVal).andAttrIdEqualTo(tbProdAttr.getId());
                List<TbProdAttrOption> attrOptions = prodAttrOptionMapper.selectByExample(ex5);
                if(attrOptions==null||attrOptions.isEmpty()){
                    tbProdAttrOption = new TbProdAttrOption();
                    tbProdAttrOption.setVal(attrOptionVal);
                    tbProdAttrOption.setAttrId(tbProdAttr.getId());
                    prodAttrOptionMapper.insertSelective(tbProdAttrOption);
                }else{
                    tbProdAttrOption = attrOptions.get(0);
                }

                TbProdSkuAttrOptionExample ex6 = new TbProdSkuAttrOptionExample();
                ex6.createCriteria().andSkuIdEqualTo(tbProdSku.getId())
                        .andAttrOptionIdEqualTo(tbProdAttrOption.getId());
                List<TbProdSkuAttrOption> prodSkuAttrOptions = prodSkuAttrOptionMapper.selectByExample(ex6);
                if(prodSkuAttrOptions==null || prodSkuAttrOptions.isEmpty()){
                    TbProdSkuAttrOption tbProdSkuAttrOption = new TbProdSkuAttrOption();
                    tbProdSkuAttrOption.setSkuId(tbProdSku.getId());
                    tbProdSkuAttrOption.setAttrOptionId(tbProdAttrOption.getId());
                    prodSkuAttrOptionMapper.insertSelective(tbProdSkuAttrOption);
                }

            }
        }

        //保存规格信息
        if(product.getSpecs()!=null) {
            for (Map.Entry<String, Map<String, String>> entry : product.getSpecs().entrySet()) {
                String groupName = entry.getKey();
                Map<String, String> specMap = entry.getValue();
                TbProdSpecGroupExample ex4 = new TbProdSpecGroupExample();
                ex4.createCriteria().andNameEqualTo(groupName);
                TbProdSpecGroup tbProdSpecGroup = null;
                List<TbProdSpecGroup> specGroups = prodSpecGroupMapper.selectByExample(ex4);
                //System.out.println("specGroups="+specGroups);
                if (specGroups == null || specGroups.size() == 0) {
                    tbProdSpecGroup = new TbProdSpecGroup();
                    tbProdSpecGroup.setName(groupName);
                    prodSpecGroupMapper.insertSelective(tbProdSpecGroup);
                } else {
                    tbProdSpecGroup = specGroups.get(0);
                }
                for (Map.Entry<String, String> specs : specMap.entrySet()) {
                    String specName = specs.getKey();
                    TbProdSpec tbProdSpec = null;
                    TbProdSpecExample ex5 = new TbProdSpecExample();
                    ex5.createCriteria().andNameEqualTo(specName);
                    List<TbProdSpec> specList = prodSpecMapper.selectByExample(ex5);
                    if (specList == null || specList.size() == 0) {
                        tbProdSpec = new TbProdSpec();
                        tbProdSpec.setName(specName);
                        tbProdSpec.setSpecGroupId(tbProdSpecGroup.getId());
                        tbProdSpec.setCateId(cate3.getId());
                        prodSpecMapper.insertSelective(tbProdSpec);
                    } else {
                        tbProdSpec = specList.get(0);
                    }
                    String specOptionVal = specs.getValue();
                    TbProdSpecOption tbProdSpecOption = null;
                    TbProdSpecOptionExample ex6 = new TbProdSpecOptionExample();
                    ex6.createCriteria().andValEqualTo(specOptionVal).andSpecIdEqualTo(tbProdSpec.getId());
                    List<TbProdSpecOption> specOptionList = prodSpecOptionMapper.selectByExample(ex6);
                    if (specOptionList == null || specOptionList.size() == 0) {
                        tbProdSpecOption = new TbProdSpecOption();
                        tbProdSpecOption.setSpecId(tbProdSpec.getId());
                        tbProdSpecOption.setVal(specOptionVal);
                        prodSpecOptionMapper.insertSelective(tbProdSpecOption);
                    } else {
                        tbProdSpecOption = specOptionList.get(0);
                    }

                    TbProdSkuSpecOption tbProdSkuSpecOption = null;
                    TbProdSkuSpecOptionExample ex7 = new TbProdSkuSpecOptionExample();
                    ex7.createCriteria().andSpecOptionIdEqualTo(tbProdSpecOption.getId())
                            .andSkuIdEqualTo(tbProdSku.getId());
                    List<TbProdSkuSpecOption> skuSpecOptionList = prodSkuSpecOptionMapper.selectByExample(ex7);
                    if (skuSpecOptionList == null || skuSpecOptionList.size() == 0) {
                        tbProdSkuSpecOption = new TbProdSkuSpecOption();
                        tbProdSkuSpecOption.setSkuId(tbProdSku.getId());
                        tbProdSkuSpecOption.setSpecOptionId(tbProdSpecOption.getId());
                        prodSkuSpecOptionMapper.insertSelective(tbProdSkuSpecOption);
                    }

                }
            }
        }


        /*

           private String cate1;
    private String cate2;
    private String cate3;
    private List<String> brands;
    private String spuId;
    private String skuId;
    private String title;
    private String brand;
    private String pname;
    private String price;
    private String img;
    private String specs;


        * */


    }




    private void saveBrands(Integer cateId,List<String>brandNames) {
        for(String brandName:brandNames){
            TbProdBrand brand = getBrand(brandName);
            if(null==brand) {
                try {
                    saveBrand(cateId, brandName);
                } catch (Exception e) {
                    continue;
                }
            }else{
                TbProdCateBrandExample ex1 = new TbProdCateBrandExample();
                ex1.createCriteria().andCateIdEqualTo(cateId)
                        .andBrandIdEqualTo(brand.getId());
                long l = prodCateBrandMapper.countByExample(ex1);
                if(l<1){
                    TbProdCateBrand tbProdCateBrand = new TbProdCateBrand();
                    tbProdCateBrand.setBrandId(brand.getId());
                    tbProdCateBrand.setCateId(cateId);
                    prodCateBrandMapper.insertSelective(tbProdCateBrand);
                }
            }
        }
    }


    private TbProdBrand getBrand(String brandName) {
        TbProdBrandExample example = new TbProdBrandExample();
        example.createCriteria().andNameEqualTo(brandName);
        List<TbProdBrand> brands = prodBrandMapper.selectByExample(example);
        if(brands==null || brands.isEmpty()) {
            return null;
        }
        return brands.get(0);
    }


    private TbProdBrand saveBrand(Integer cateId,String brandName){


                //将品牌入库
                TbProdBrand prodBrand = new TbProdBrand();
                prodBrand.setName(brandName);
                prodBrandMapper.insertSelective(prodBrand);
                prodBrand.setCode(""+prodBrand.getId());
                prodBrandMapper.updateByPrimaryKeySelective(prodBrand);

                //将分类与品牌的关联入库
                TbProdCateBrand prodCateBrand = new TbProdCateBrand();
                prodCateBrand.setCateId(cateId);
                prodCateBrand.setBrandId(prodBrand.getId());
                prodCateBrandMapper.insert(prodCateBrand);
                return prodBrand;

    }


}
